package com.neuedu.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author 许中
 * @date 2024-09-03 14:08:58
 */
public class DigestUtil {
    public static String md5(String in){
        byte[] bytes = in.getBytes();
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] result = md5.digest(bytes);
            //把字节数组转换为16进制字符串。
            String s = bytesToHex(result);
            return s.toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String sha1(String in){
        byte[] bytes = in.getBytes();
        try {
            MessageDigest md5 = MessageDigest.getInstance("SHA1");
            byte[] result = md5.digest(bytes);
            //把字节数组转换为16进制字符串。
            String s = bytesToHex(result);
            return s.toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String bytesToHex(byte[] bytes){
        StringBuilder sb=new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String s = Integer.toHexString(0xff&bytes[i]);
            if(s.length()==1){
                sb.append('0');
            }
            sb.append(s);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
//        System.out.println(md5("123456"));
//        System.out.println(sha1("123456"));
//        for (int i = 0; i <= 255; i++) {
//            System.out.println(Integer.toHexString(0xff&i));
//        }
    }
}


